<?php

namespace App\Http\Middleware;

use App\Models\AdminUser;
use Closure;

class AdminLogin
{
    /**
     * 检查管理员是否登陆
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->session()->has('adminUser')){
            $userInfo = $request->session()->get('adminUser',null);
            $now = time();
            if($userInfo->expire_in < $now){
                return redirect('admin/login');
            }
            if($userInfo->refersh_time < $now){
                //刷新数据
                $userModel = new AdminUser();
                $user = $userModel->where('id',$userInfo->id)
                    ->select(['id','account','nickname','sex','tel','name','avatar','status'])
                    ->first();
                if( (!$user) || ($user->id != 1 && $user->status != 1)){
                    $request->session()->forget('adminUser');
                    return redirect('admin/login');
                }
                $refreshTime = $now + config('systemSetting.admin.adminRefreshTime',3600);
                $expireTime = $now + config('systemSetting.admin.adminExpireTime',36000);
                $user->refresh_time = $refreshTime;
                $user->expire_in = $expireTime;
                $request->session()->put('adminUser',$user);
            }

        }else{
            return redirect('admin/login');
        }
        return $next($request);
    }
}
